package com.nota.flink.cdc.utils;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * @author 胡超雄
 * @date 2023/11/10 17:11
 * @desc
 */
@Component
@Slf4j
public class DingUtils {

    @Value("${dingding.url}")
    private String dingUrl;

    @Async("statisticDingMsg")
    public Boolean sendToDing(String title, String message) {
        try {
            String profile = SpringUtil.getActiveProfile();
            if ("test".equals(profile) || "local".equals(profile)) {
                return false;
            }
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/json");
            JSONObject msg = new JSONObject();
            msg.put("msgtype", "markdown");
            JSONObject markdown = new JSONObject();
            markdown.put("text", "NOTA-FLINK-CDC[" + message + "]");
            markdown.put("title", title);
            msg.put("markdown", markdown);
            HttpEntity<String> requestEntity = new HttpEntity<>(msg.toString(), headers);
            RestTemplate restTemplate = new RestTemplate();
            restTemplate.postForObject(dingUrl, requestEntity, JSONObject.class);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return true;
    }
}
